package com.flysky.dao.user.impl;



import java.util.HashMap;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.flysky.dao.BaseDao;
import com.flysky.dao.user.IUserDao;
import com.flysky.model.user.UserHbmModel;

public class UserHibernateDaoImpl extends BaseDao implements IUserDao {

	@Override
	public UserHbmModel insertUser(UserHbmModel newUser) {
		Session session = null;
		Transaction tx = null;
		try{
			session = this.sessionFactory.openSession();
			tx = session.beginTransaction();
			session.save(newUser);
			tx.commit();
		}finally{
			session.close();
		}
		return newUser;
	}

	@Override
	public UserHbmModel findUser(HashMap<String, String> param) {
		Session session = null;
		UserHbmModel userModel = null;
		try{
			session = this.sessionFactory.openSession();
			String hql = "from UserHbmModel where name = :name and password = :password";
			Query query = session.createQuery(hql);
			query.setParameter("name", param.get("name"));
			query.setParameter("password", param.get("password"));
			userModel = (UserHbmModel) query.uniqueResult();
		}finally{
			session.close();
		}
		return userModel;
	}

	@Override
	public UserHbmModel saveOrUpdateUser(UserHbmModel userModel) {
		Session session = null;
		Transaction tx = null;
		try{
			session = this.sessionFactory.openSession();
			tx = session.beginTransaction();
			session.saveOrUpdate(userModel);
			tx.commit();
		}finally{
			session.close();
		}
		return userModel;
	}

}
